#include "u_thread.h"
#include "udpserver.h"
#include "udpunit.h"
#include "../util/lock.h"
#include "../util/timer.h"

void uc_Sleep(uint32 seconds)
{
	struct timespec ts, rmts;
	
	ts.tv_sec = seconds/1000;
	ts.tv_nsec = (seconds%1000)*1000000;
	while(1)
	{
		int ret = nanosleep(&ts, &rmts);
		if(ret == 0) 
		{
			break;
		}

		int sleepErr = errno;
		if(ret == -1 && sleepErr == EINTR)
		{
			ts = rmts;
		}
	}
}

uthread::uthread(UDPSINK* udpsink,usocket* udp)
{
	func_lock s_lock;
  m_sink = udpsink;
  m_udp  = udp;
  m_log  = new logfile("uthread");
  m_event.Initevent(m_udp->get_socket());
  InitThread(false);
}
    
uthread::~uthread()
{
	func_lock s_lock;
	StopThread();
	m_sink = NULL;
	m_udp  = NULL;
}

void uthread::Execute()
{
	uint32 ip;
	uint16 port;
	char   tmpbuf[1500] ;
	uint16 buf_size;
	m_event.SetupSocketevent();

	while(m_finished == false)
	{
		if(m_event.WaitSocketevent())
		{
			if(m_udp->recvbuf(&ip,&port,tmpbuf,&buf_size) == false)
				continue;

			if(buf_size > 15 && buf_size < 1500)
			{
				if(CheckBuffer(tmpbuf,buf_size))
				{
					uint32 time = get_time();
					m_sink->OnRead(ip,port,tmpbuf + UPDHeadSize ,buf_size - UPDHeadSize);
					if(get_time() -time > 0)
					{
						char llr[1023] = {0};
						sprintf(llr,"udp read time=%d,time=%d",
							get_time() -time,get_time());
						m_log->WriteTrace(llr);
					}
					continue;
				}
			}

			m_sink->OnReadError(ip,port,tmpbuf,buf_size);
		}			
	}
}

